<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数{{ total }}</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >导入excel</el-button>
          <el-button
            v-allow="'导出Excel'"
            type="danger"
            size="small"
            @click="handleDownload"
          >导出excel</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click.native="dialogFormVisible=true"
          >新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="rules" :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="username">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100%">
              <template /></template></el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ FormDataemployees(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="correctionTime" sortable>
            <template #default="{row}">
              {{ formaDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hassignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="dodelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :current-page="page"
            :page-size="size"
            :page-sizes="[2,5,10,20,50]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
      <!-- 按钮弹层 -->
      <el-dialog title="新增或编辑" :visible.sync="dialogFormVisible" @close="hCloseDialog">
        <addor-Edit ref="AddEmployee" @success="addlist" @aaa="abc" />
      </el-dialog>
      <!-- 角色弹层 -->
      <el-dialog
        v-if="showDialogRole"
        :visible.sync="showDialogRole"
        title="分配角色"
      >
        <assignRole :employe-id="employeId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployeeList, deleteloyeeList } from '@/api/employees'
import employees from '@/constant/employees'
import addorEdit from './empDialog.vue'
import assignRole from './assignRole.vue'
import dayjs from 'dayjs'
const hireType = employees.hireType.reduce((sum, item) => {
  sum[item.id] = item.value
  return sum
}, {})
export default {
  components: {
    addorEdit,
    assignRole
  },
  data() {
    return {
      // 父传子id属性
      employeId: '',
      // 分页数据
      page: 1,
      size: 2,
      total: 0,
      // 接收列表信息
      rules: [],
      // 弹层开关
      dialogFormVisible: false,
      // 角色弹层开关
      showDialogRole: false
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 格式化EXCeL需要的数据
    formData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出一个数据对象
      const one = list[0]
      // 判断one是否有值，如果没有直接终止程序
      if (!one) {
        //   list中没有数据
        return
      }
      console.log(Object.keys(one))
      // 使用对象生成需要的header数据
      const header = Object.keys(one).map(enKey => {
        return map[enKey]
      })
      console.log(header)

      const data = list.map(item => {
        //    item['formOfEmployment'] ====> 1 或者 2
        // hireType===> {1:'正式',2:'非正式'}
        item['formOfEmployment'] = hireType[ item['formOfEmployment']] || '未知'
        item['correctionTime'] = item['correctionTime'] || '-'

        return Object.values(item)
      })

      return { header, data }
    },
    // 导出excl表格函数
    async handleDownload() {
      // import('@/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
      //   const filterVal = [[1, '第一条数据', 'summer', '222', '2022-07-18'], [2, '第二条数据', 'summer1', '333', '2022-07-18']]
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data: filterVal,
      //     filename: this.filename,
      //     autoWidth: this.autoWidth,
      //     bookType: this.bookType
      //   })
      // })
      // 1.发送请求
      const res = await getEmployeeList(this.page, this.size)
      console.log(res.data.rows, '全部信息')
      // 2.转化数据格式
      const { header, data } = this.formData(res.data.rows)
      // 3.调用核心代码,生成excel
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: header, // 表头 必填
          data: data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 格式化时间
    formaDate(timer) {
      return dayjs(timer).format('YYYY-MM-DD')
    },
    // 格式化聘用形式
    FormDataemployees(val) {
      // const result = employees.hireType.find(item => item.id === val)
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }
      // const hireType = {}
      // employees.hireType.forEach(item => {
      //   hireType[item.id] = item.value
      // })

      return hireType[val] ? hireType[val] : '未知'
    },
    // 分页函数
    // 页码
    hCurrentChange(val) {
      this.page = val
      this.loadEmployeeList()
    },
    // 每页条数
    hSizeChange(val) {
      this.size = val
      this.loadEmployeeList()
    },
    // 全部列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        this.rules = res.data.rows
        this.total = res.data.total
        console.log(res, '全部信息')
      } catch (error) {
        console.log(error)
      }
    },
    // 删除函数
    async deleteList(id) {
      try {
        await deleteloyeeList(id)
        if (this.rules.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    // 确认删除
    dodelete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteList(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 确认新增
    addlist() {
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.dialogFormVisible = false
      this.loadEmployeeList()
    },
    //  子传父取消事件
    abc() {
      this.dialogFormVisible = false
      this.loadEmployeeList()
    },
    // close事件
    hCloseDialog() {
      this.$refs.AddEmployee.resetForm()
    },
    // 角色弹层开关
    hassignRole(id) {
      this.showDialogRole = true
      this.employeId = id
    }
  }
}
</script>
